<style type="text/css">
	.layui-table-cell{
		height: auto; /* Layui的表格高度自适应 */
	}
	
	.layui-table-cell img{
		width: 60px;
		height: 60px;
	}
</style>

<style>
	#demo2 img{
		width: 92px;
		height: 92px;
	}
	#demo2 span{
		position: relative;
	}
	#demo2 span:hover::after{
		content: "X";
		display: block;
		background-color: #FF5722;
		width: 16px;
		height: 16px;
		border-radius: 16px;
		position: absolute;
		line-height: 16px;
		color: #fff;
		text-align: center;
		top: -46px;
		right: 0px;
	}
</style>

<fieldset class="layui-elem-field layui-field-title">
  <legend>商品列表</legend>
</fieldset>

<table id="list" lay-filter="list"></table>

<script type="text/html" id="bar">
	{{# if (d.status==1) {  }}
	<a class="layui-btn layui-btn-sm" lay-event="recover">恢复</a>
	{{# } }}
	{{# if (d.status==0) { }}
	<a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete">删除</a>
	{{# } }}
	<a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="edit">编辑</a>
</script>

<script type="text/html" id="pictures">
	{{#
	for (var i=0; i<d.pictures.length; i++) {
	}}
	<img src="/adminServer/upload/{{d.pictures[i].name}}">
	{{#
	}
	}}
</script>

<!-- 编辑时的表单 -->
<script type="text/html" id="edit">
	<form class="layui-form" style="width: 620px;">
		<!-- 放商品的ID -->
		<input type="hidden" name="id"/>
		<div class="layui-form-item">
			<label class="layui-form-label">商品名称</label>
			<div class="layui-input-inline">
				<input type="text" name="name" class="layui-input" placeholder="请输入分类名" />
			</div>
			<label class="layui-form-label">商品价格</label>
			<div class="layui-input-inline">
				<input type="number" name="price" class="layui-input" placeholder="请输入商品价格" />
			</div>
		</div>
		
		<div class="layui-form-item">
			<label class="layui-form-label">一级分类</label>
			<div class="layui-input-inline">
				<select name="parent" lay-filter="parent"></select>
			</div>
			<label class="layui-form-label">二级分类</label>
			<div class="layui-input-inline">
				<select name="goodsSortId">
					<option value=''>请选择二级分类</option>
				</select>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">商品版本</label>
			<div class="layui-input-inline">
				<input type="text" name="version" class="layui-input" placeholder="请输入商品版本" />
			</div>
			<label class="layui-form-label">商品颜色</label>
			<div class="layui-input-inline">
				<input type="text" name="color" class="layui-input" placeholder="请输入商品颜色" />
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">商品套餐</label>
			<div class="layui-input-inline">
				<input type="text" name="suit" class="layui-input" placeholder="请输入商品套餐" />
			</div>
			<label class="layui-form-label">商品库存</label>
			<div class="layui-input-inline">
				<input type="number" name="count" class="layui-input" placeholder="请输入商品库存" />
			</div>
		</div>
		
		
		<div class="layui-form-item">
			<label class="layui-form-label">商品描述</label>
			<div class="layui-input-block">
				<textarea name="dscp" placeholder="请输入内容" class="layui-textarea"></textarea>
			</div>
		</div>
		
		<div class="layui-form-item" >
			<label class="layui-form-label">商品图片</label>
			<div class="layui-input-block">
				<!-- 使用layui的上传图片的插件 -->
				<div class="layui-upload">
				  <button type="button" class="layui-btn" id="test2">图片上传</button> 
				  <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
				    预览图：
				    <div class="layui-upload-list" id="demo2"></div>
				 </blockquote>
				</div>
			</div>
		</div>
		
		<div class="layui-form-item">
			<label class="layui-form-label"></label>
			<div class="layui-input-inline">
				<button type="submit" class="layui-btn layui-btn-danger" 
					lay-submit lay-filter="edit">修改商品</button>
			</div>
		</div>
		
	</form>
</script>

<script type="text/javascript">
	layui.use(['table', 'form', 'upload'], function(){
		var table = layui.table;
		var form = layui.form;
		var upload = layui.upload;
		
		
		// Ajax异步请求数据, 渲染表格
		table.render({
			id: 'list',	// 刷新用的
			elem: '#list',
			url: '/adminServer/api/goods',
			method: 'get',
			height: 500,
			page: true,	// 开启分页
			cols: [[
				{field: 'id', title: 'ID', width: 100},
				{field: 'name', title: '商品名',},
				{title: '图片', templet: '#pictures', width:300},
				{field: 'dscp', title: '描述',},
				{field: 'price', title: '价格',},
				{field: 'version', title: '版本',},
				{field: 'color', title: '颜色',},
				{field: 'suit', title: '套餐',},
				{field: 'count', title: '库存',},
				{field: 'goodsSortId', title: '一级分类', templet: function(d){
					return d.goodsSort.parentSort.name;
				}},
				{field: 'goodsSortId', title: '二级分类', templet: function(d){
					return d.goodsSort.name;
				}},
				{field: 'status', title: '状态', templet: function(d){
					return ['正常', '删除'][d.status];
				}, width: 100},
				{title: '操作', toolbar: '#bar', width: 150, fixed: 'right'}
			]],
			// 解析数据
			parseData: function(res){
				return {
					"code": 0,
					"msg": res.msg,
					"count": res.data.total,
					"data": res.data.list
				};
			},
			done: function(res, curr, count){
				// 固定列高度适应
				$(".layui-table-main  tr").each(function (index ,val) {
					$($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
				});
			}
		});
		
		/* 绑定表格的工具条事件 */
		table.on('tool(list)', function(obj){
			// obj 工具条所在的一行的数据
			var data = obj.data; //获得当前行数据
			var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
			var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
			
			if (layEvent == 'delete'){
				// alert("删除")
			} else if (layEvent == 'edit'){
				// 弹出一个窗口, 提供表单
				var index = layer.open({
					type: 1, 	// 页面层
					title: '编辑商品',
					area: ['800px', '500px'],	// 0.618
					content: $("#edit").html(), 
				});
				
				// 将表格中的数据, 渲染到表单上
				$("input[name='id']").val(data.id);
				$("input[name='name']").val(data.name);
				$("textarea[name='dscp']").val(data.dscp);
				$("input[name='price']").val(data.price);
				$("input[name='version']").val(data.version);
				$("input[name='color']").val(data.color);
				$("input[name='suit']").val(data.suit);
				$("input[name='count']").val(data.count);
				
				/* 表单提交事件 */
				// 表单提交
				form.on('submit(edit)', function(data){
					
					// 获取所有的图片, 组成一个数组
					var pictures = [];
					$("input[name='picture']").each(function(){
						pictures.push( {name: $(this).val()} );
					});
					
					// 将数组放到data.field中
					data.field.pictures = pictures;
					
					$.ajax({
						url: '/adminServer/api/goods',
						type: 'put',
						data: JSON.stringify(data.field),
						contentType: 'application/json; charset=utf-8',
						dataType: 'json',
						success: function(data){
							if (data.status==201){
								// 关闭弹窗
								layer.close(index);
								// 刷新table
								table.reload("list");
							} else {
								layer.msg(data.msg||data.message);
							}
						},
						error: function(){					
						}
					});
					
					return false;
				});
				
				$.each(obj.data.pictures, function(index, item){
					$('#demo2').append('<span><img src="/adminServer/upload/'+ item.name +'" class="layui-upload-img">' +
														'<input type="hidden" name="picture" value="'+item.name+'"></span>')
				});
				//多图片上传
				upload.render({
				    elem: '#test2'
				    ,url: '/adminServer/api/upload' //此处配置你自己的上传接口即可
				    ,multiple: true
				    ,done: function(res){
				      //上传完毕 // 每一上传一张图片, 都会响应一次
					  $('#demo2').append('<span><img src="/adminServer/upload/'+ res.data +'" class="layui-upload-img">' +
										'<input type="hidden" name="picture" value="'+res.data+'"></span>')
					  
				    }
				});
				
				// 添加图片点击事件
				$("#demo2").on("click", "span", function(){
					$(this).remove();
				});
				
				// 一级分类, 二级分类
				// 获取一级分类
				$.ajax({
					url: '/adminServer/api/goodsSorts',
					type: 'get',
					data: {},
					dataType: 'json',
					success: function(data){
						
						if (data.status == 200){
							var html = "<option value=''>请选择一级分类</option>";
							$.each(data.data.list, function(index, item){
								if (item.id == obj.data.goodsSort.parentSort.id){
									html += "<option value='"+item.id+"' selected='selected'>"+item.name+"</option>";
								} else {
									html += "<option value='"+item.id+"'>"+item.name+"</option>";
								}
								
							});
							$("select[name='parent']").html(html);
							
							// 渲染表单
							form.render();
							
							// 初始化二级分类
							// 获取二级分类
							$.ajax({
								url: '/adminServer/api/goodsSorts',
								type: 'get',
								data: {parent: obj.data.goodsSort.parentSort.id},
								dataType: 'json',
								success: function(data){
									
									if (data.status == 200){
										var html = "<option value=''>请选择二级分类</option>";
										$.each(data.data.list, function(index, item){
											if (item.id == obj.data.goodsSortId){
												html += "<option value='"+item.id+"' selected='selected'>"+item.name+"</option>";
											} else {
												html += "<option value='"+item.id+"'>"+item.name+"</option>";
											}
										});
										$("select[name='goodsSortId']").html(html);
										
										// 渲染表单
										form.render();
									} else {
										layer.alert(data.msg);
									}
								},
								error: function(){
									
								}
							});
							
							// 联动
							// 二级分类联动
							form.on('select(parent)', function(data){
								// 获取点击的一级分类
								var parent = data.value;
								
								if (parent > 0){
								
									// 获取二级分类
									$.ajax({
										url: '/adminServer/api/goodsSorts',
										type: 'get',
										data: {parent: parent},
										dataType: 'json',
										success: function(data){
											
											if (data.status == 200){
												var html = "<option value=''>请选择二级分类</option>";
												$.each(data.data.list, function(index, item){
													html += "<option value='"+item.id+"'>"+item.name+"</option>";
												});
												$("select[name='goodsSortId']").html(html);
												
												// 渲染表单
												form.render();
											} else {
												layer.alert(data.msg);
											}
										},
										error: function(){
											
										}
									});
								} else {
									$("select[name='goodsSortId']").html("<option value=''>请选择二级分类</option>");
									// 渲染表单
									form.render();
								}
							});
						}
					},
					error: function(){
						
					}
				});
				
			}
		});
	});
</script>